package cn.itrip.auth.service;


import cn.itrip.auth.exception.UserLoginFailedException;
import cn.itrip.beans.pojo.ItripUser;
import cn.itrip.comment.EmptyUtils;
import cn.itrip.comment.MD5;
import cn.itrip.comment.RedisAPI;
import cn.itrip.dao.user.ItripUserMapper;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 用户管理接口的实现
 * @author hduser
 *
 */
@Service("useService")
public class UserServiceImpl implements UserService {

	@Resource
	private ItripUserMapper itripUserMapper;

	@Resource
	private MailService mailService;

	@Resource
	private RedisAPI redisAPI;

	@Resource
	private SmsService smsService;

	//过期时间（分钟）
	private int expire=30;

	private Logger logger=Logger.getLogger(UserServiceImpl.class);

	/**
	 * 根据用户名查询用户信息
	 */
	@Override
	public ItripUser findByUsername(String username) throws Exception {
		Map<String, Object> param=new HashMap();
		param.put("userCode", username);
		List<ItripUser> list = itripUserMapper.getItripUserListByMap(param);
		if(list.size()>0) {
			return list.get(0);
		} else {
			return null;
		}
	}

	@Override
	public void itriptxCreateUser(ItripUser user) throws Exception {

		//发送激活邮件
		String activationCode = MD5.getMd5(new Date().toLocaleString(), 32);
		mailService.sendActivationMail(user.getUserCode(), activationCode);
		//保存用户信息
		itripUserMapper.insertItripUser(user);
	}

	@Override
	public boolean activate(String email, String code) throws Exception {
		String key="activation:"+email;
		if(redisAPI.exist(key)) {
			if(redisAPI.get(key).equals(code)){
				ItripUser user=this.findByUsername(email);
				if(EmptyUtils.isNotEmpty(user))
				{
					logger.debug("激活用户"+email);
					//激活用户
					user.setActivated(1);
					//自注册用户
					user.setUserType(0);
					user.setFlatID(user.getId());
					itripUserMapper.updateItripUser(user);
					return true;
				}
			}
		}

		return false;
	}

	@Override
	public void itriptxCreateUserByPhone(ItripUser user) throws Exception {
		//发送短信验证码
		String code=String.valueOf(MD5.getRandomCode());
		smsService.send(user.getUserCode(), "1", new String[]{code,String.valueOf(expire)});
		//缓存验证码
		String key="activation:"+user.getUserCode();
		redisAPI.set(key, expire*60, code);
		//保存用户信息
		itripUserMapper.insertItripUser(user);
	}

	@Override
	public boolean validatePhone(String phoneNumber, String code) throws Exception{
		String key  = "activation:"+phoneNumber;
		if (redisAPI.exist(key)){
			if (redisAPI.get(key).equals(code)){
                ItripUser user=this.findByUsername(phoneNumber);
                if (EmptyUtils.isNotEmpty(user)){
                    logger.debug("用户手机验证已通过："+phoneNumber);
                    //激活用户
                    user.setActivated(1);
                    //自注册用户
                    user.setUserType(0);
                    user.setFlatID(user.getId());
                    itripUserMapper.updateItripUser(user);
                    return true;
                }
			}
		}
		return false;
	}

    @Override
    public ItripUser login(String name, String password) throws Exception {
        ItripUser user = findByUsername(name);
        if (null != user && user.getUserPassword().equals(password)){
            if (user.getActivated()!=1){
                throw new UserLoginFailedException("用户未激活");
            }
            return user;
        }
        return null;
    }


}